using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using NBlock.Components.Excel;
using NBlock.Core;
using NBlock.MVCExtensions;

namespace Cost.Controllers
{
    public class EnumController : Controller
    {
        #region 构造函数
        private readonly ICostRepository<EnumItem> enumitemRepository;
        private readonly ICostRepository<EnumType> enumTypeRepository;
        private readonly IExcelImporter excelImporter;

        public EnumController(ICostRepository<EnumItem> enumitemRepository,
            ICostRepository<EnumType> enumTypeRepository,
            IExcelImporter excelImporter)
        {
            this.enumitemRepository = enumitemRepository;
            this.enumTypeRepository = enumTypeRepository;
            this.excelImporter = excelImporter;
        }
        #endregion

        //
        // GET: /Enum/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Enum/Edit/5

        public ActionResult Edit(string Id, string parentId)
        {
            var data = enumitemRepository.Find(Id) ?? new EnumItem();
            if (string.IsNullOrEmpty(data.TypeId))
            {
                data.TypeCode = parentId;
                var type = enumTypeRepository.Find(t => t.TypeCode == parentId);
                if (type != null)
                    data.TypeId = type.Id;

                data.SeqNo = 9999;
            }
            return View(data);
        }

        //
        // POST: /Enum/Save

        [HttpPost]
        public JsonResult Save(string Id)
        {
            var data = enumitemRepository.Find(Id) ?? new EnumItem();
            TryUpdateModel(data);
            data.TypeCode = data.TypeCode ?? data.ParentId;
            enumitemRepository.Save(data);
            return Json(nbAjaxMessage.Successful);
        }

        //
        // POST: /Enum/Delete/5

        [HttpPost]
        public JsonResult Delete(string Id)
        {
            enumitemRepository.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAll(string Ids)
        {
            var items = Ids.Split(',');
            enumitemRepository.DeleteAll(t => items.Contains(t.Id));
            return Json(nbAjaxMessage.Successful);
        }

        //
        // POST: /Enum/List

        [HttpPost]
        public JsonResult List(string type, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = enumitemRepository.GetPageable(pager, e => e.TypeCode == type, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        //
        // POST: /Enum/Tree

        [HttpPost]
        public JsonResult Tree(string Id)
        {
            var list = new List<nbJsonTreeNode>();
            if (string.IsNullOrWhiteSpace(Id))
            {
                list = enumTypeRepository.FindAll().OrderBy(t => t.SeqNo).Select(t => new nbJsonTreeNode
                {
                    id = t.TypeCode,
                    text = t.TypeName,
                    value = t.TypeCode,
                    isexpand = false,
                    complete = true,
                }).ToList();
            }
            return Json(list);
        }

        /// <summary>
        /// 获取拼首码
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public JsonResult GetFirstChar(string Id, string name)
        {
            var firstPY = string.Empty;
            if (!string.IsNullOrWhiteSpace(name))
            {
                firstPY = HZ2PY.GetFirstPY(name);
            }
            return Json(nbAjaxMessage.Successful.SetData(firstPY));
        }

        #region 数据导入
        public ActionResult Import(string excelKey)
        {
            ViewBag.TemplateUrl = excelImporter.GetExcelTemplateUrl(excelKey);
            ViewBag.ExcelKey = excelKey;
            return View();
        }

        [HttpPost]
        public nbFileUploadJsonResult Import(HttpPostedFileBase file, string ExcelKey, string UpdateMode)
        {
            try
            {
                // 保留导入文档，以便后续检查
                var path = Server.MapPath("~/Upload/") + System.IO.Path.GetFileName(file.FileName).Replace(".", "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".");
                file.SaveAs(path);

            }
            catch (Exception ex)
            {
                // TODO 记录日志
            }

            var data = excelImporter.Import(file, ExcelKey);
            foreach (var row in data.RepeatData.Rows)
            {
                var item = row.ToEntity<EnumItem>();
                var oldItem = enumitemRepository.Find(i => i.EnumName == item.EnumName && i.TypeCode == item.TypeCode);
                if (oldItem != null)
                {
                    item = row.ToEntity(oldItem);
                }
                else
                {
                    item.FirstChar = NBlock.Core.HZ2PY.GetFirstPY(item.EnumName);
                    var type = enumTypeRepository.Find(t => t.TypeCode == item.TypeCode);
                    if (type != null)
                        item.TypeId = type.Id;

                    if (string.IsNullOrWhiteSpace(item.EnumCode))
                    {
                        item.EnumCode = HZ2PY.ConvertPY(item.EnumName);
                        var count = enumitemRepository.FindAll(i => i.EnumCode == item.EnumCode && i.Id != item.Id).Count();
                        if (count > 0)
                        {
                            item.EnumCode = item.EnumCode + count.ToString();
                        }
                    }
                }

                enumitemRepository.Save(item);
            }
            return new nbFileUploadJsonResult { Data = nbAjaxMessage.Successful };
        }
        #endregion

        #region 子枚举
        public ActionResult SubItem(string parentId)
        {
            ViewBag.ParentId = parentId;
            return View();
        }

        public ActionResult EditSubItem(string Id, string parentId)
        {
            var data = enumitemRepository.Find(Id) ?? new EnumItem();
            if (string.IsNullOrEmpty(data.TypeId))
            {
                data.ParentId = parentId;
                var parentItem = enumitemRepository.Find(parentId);
                if (parentItem != null)
                {
                    data.ParentCode = parentItem.EnumCode;
                    data.TypeCode = parentItem.TypeCode;
                    data.TypeId = parentItem.TypeId;
                }

                data.SeqNo = 9999;
            }
            return View("Edit", data);
        }

        [HttpPost]
        public JsonResult SubItemList(string parentId, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = enumitemRepository.GetPageable(pager, e => e.ParentId == parentId, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }
        #endregion

        #region 枚举类型
        public ActionResult EnumType()
        {
            return View();
        }

        public ActionResult EditEnumType(string Id)
        {
            var data = enumTypeRepository.Find(Id) ?? new EnumType();
            data.SeqNo = data.SeqNo ?? 9999;
            return View(data);
        }

        [HttpPost]
        public JsonResult SaveEnumType(string Id)
        {
            var data = enumTypeRepository.Find(Id) ?? new EnumType();
            TryUpdateModel(data);
            enumTypeRepository.Save(data);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteEnumType(string Id)
        {
            enumTypeRepository.Delete(Id);
            enumitemRepository.DeleteAll(t => t.TypeId == Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteEnumTypes(string Ids)
        {
            var items = Ids.Split(',');
            enumTypeRepository.DeleteAll(t => items.Contains(t.Id));
            enumitemRepository.DeleteAll(t => items.Contains(t.TypeId));
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult EnumTypeList(nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = enumTypeRepository.GetPageable(pager, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        [HttpPost]
        public JsonResult GetTypeCode(string name)
        {
            var code = string.Empty;
            if (!string.IsNullOrWhiteSpace(name))
            {
                code = HZ2PY.ConvertPY(name);
            }
            return Json(nbAjaxMessage.Successful.SetData(code));
        }
        #endregion
    }
}

